package calvin.study.rabbitmq.advanced.confirm;

import java.io.IOException;

import com.rabbitmq.client.CancelCallback;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DeliverCallback;
import com.rabbitmq.client.Delivery;

import calvin.study.rabbitmq.base.RabbitMqBase;

public class Consumer extends RabbitMqBase {
	
	private final static String  EXCHANGE_TYPE = "topic";
	
	public static void main(String[] args) throws Exception {

		// 1 创建ConnectionFactory
		ConnectionFactory connectionFactory = getConnectionFactory();

		// 2 获取C onnection
		Connection connection = connectionFactory.newConnection();

		// 3 通过Connection创建一个新的Channel
		Channel channel = connection.createChannel();

		String exchangeName = "confirm_topic_exchange";
		String routingKey = "confirm.#";
		String queueName = "confirm_queue";

		// 4 声明交换机和队列 然后进行绑定设置, 最后制定路由Key
		channel.exchangeDeclare(exchangeName, EXCHANGE_TYPE, true);
		channel.queueDeclare(queueName, true, false, false, null);
		channel.queueBind(queueName, exchangeName, routingKey);

		// 5 创建消费者
		//QueueingConsumer queueingConsumer = new QueueingConsumer(channel);
		//channel.basicConsume(queueName, true, queueingConsumer);
		channel.basicConsume(queueName, true, new DeliverCallback() {
			@Override
			public void handle(String consumerTag, Delivery message) throws IOException {
				System.out.println(message.getProperties().getCorrelationId());
				System.out.println(queueName + "收到的消息是：" + new String(message.getBody(), "UTF-8"));

			}
			
		} , new CancelCallback() {
			@Override
			public void handle(String consumerTag) throws IOException {
				System.err.println("消息接收失败");
			}
		});
	}
}
